<template>
    <div class="login-container">
        <div class="login-card">
            <!-- Left side - Illustration -->
            <div class="illustration-section">
                <div class="illustration">
                    <div class="monitor">
                        <div class="screen">
                            <div class="code-lines">
                                <div class="line"></div>
                                <div class="line"></div>
                                <div class="line"></div>
                                <div class="line"></div>
                            </div>
                            <div class="code-tag">&lt;/&gt;</div>
                        </div>
                    </div>
                    <div class="gears">
                        <div class="gear gear-1">⚙️</div>
                        <div class="gear gear-2">⚙️</div>
                    </div>
                    <div class="person person-left">
                        <div class="person-body"></div>
                        <div class="person-head"></div>
                    </div>
                    <div class="person person-right">
                        <div class="person-body"></div>
                        <div class="person-head"></div>
                    </div>
                    <div class="database">
                        <div class="db-layer"></div>
                        <div class="db-layer"></div>
                        <div class="db-layer"></div>
                    </div>
                </div>
            </div>

            <!-- Right side - Login Form -->
            <div class="form-section">
                <h2 class="system-title">ERP&MES生产制造管理综合系统</h2>

                <form @submit.prevent="handleLogin" class="login-form">
                    <div class="form-group">
                        <input v-model="loginForm.username" type="text" placeholder="请输入用户名" class="form-input"
                            required />
                    </div>

                    <div class="form-group">
                        <input v-model="loginForm.password" type="password" placeholder="请输入登录密码" class="form-input"
                            required />
                    </div>

                    <div class="form-group">
                        <div class="captcha-group">
                            <input v-model="loginForm.captcha" type="text" placeholder="请输入验证码"
                                class="form-input captcha-input" required />
                            <div class="captcha-display" @click="refreshCaptcha">
                                {{ captchaText }}
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="login-button" :disabled="isLoading">
                        {{ isLoading ? '登录中...' : '登录' }}
                    </button>
                </form>

                <div v-if="errorMessage" class="error-message">
                    {{ errorMessage }}
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {MES_XHY_ApiHost} from '../utils/Interceptors'

const router = useRouter()

// 表单数据
const loginForm = ref({
    username: '',
    password: '',
    captcha: ''
})

// 验证码
const captchaText = ref('')
const isLoading = ref(false)
const errorMessage = ref('')

// 生成随机验证码
const generateCaptcha = () => {
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    let result = ''
    for (let i = 0; i < 4; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return result
}

// 刷新验证码
const refreshCaptcha = () => {
    captchaText.value = generateCaptcha()
}

// 处理登录
const handleLogin = async () => {
    errorMessage.value = ''

    // 验证验证码
    if (loginForm.value.captcha.toLowerCase() !== captchaText.value.toLowerCase()) {
        errorMessage.value = '验证码错误'
        refreshCaptcha()
        return
    }

    isLoading.value = true

    try {
        // 调用真实API登录接口
        const response = await MES_XHY_ApiHost.post('/api/Login/login', {
            Account: loginForm.value.username,
            Password: loginForm.value.password
        })

        if (response.data.code === 200) {
            // 登录成功，保存用户信息到sessionStorage（关闭浏览器后失效）
            const userData = response.data.data
            sessionStorage.setItem('user', JSON.stringify(userData))
            sessionStorage.setItem('isLoggedIn', 'true')

             sessionStorage.setItem('id',response.data.data.Id)

             console.log(response.data);
             

            // 如果API返回了token，也保存到sessionStorage
            if (userData.token) {
                sessionStorage.setItem('token', userData.token)
            }

            // 跳转到主页
            router.push('/home')
        } else {
            errorMessage.value = response.data.msg || '登录失败'
        }
    } catch (error: any) {
        console.error('登录错误:', error)
        if (error.response?.data?.msg) {
            errorMessage.value = error.response.data.msg
        } else if (error.message) {
            errorMessage.value = error.message
        } else {
            errorMessage.value = '网络错误，请稍后重试'
        }
    } finally {
        isLoading.value = false
    }
}

// 组件挂载时生成验证码并清除之前的登录状态
onMounted(() => {
    // 清除所有登录相关的存储信息，确保每次访问都需要重新登录
    sessionStorage.removeItem('user')
    sessionStorage.removeItem('isLoggedIn')
    sessionStorage.removeItem('token')
    localStorage.removeItem('user')
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('token')
    
    refreshCaptcha()
})
</script>

<style scoped>
/* 全局禁用滚动 */
:global(html, body) {
    height: 100%;
    overflow: hidden;
    margin: 0;
    padding: 0;
}

:global(#app) {
    height: 100vh;
    overflow: hidden;
}

.login-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    overflow: hidden;
    box-sizing: border-box;
}

.login-card {
    background: white;
    border-radius: 20px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    display: flex;
    overflow: hidden;
    max-width: 900px;
    width: 100%;
    height: 500px;
    max-height: calc(100vh - 40px);
    box-sizing: border-box;
}

.illustration-section {
    flex: 1;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px;
    position: relative;
}

.illustration {
    position: relative;
    width: 300px;
    height: 250px;
}

.monitor {
    position: absolute;
    top: 20px;
    left: 50px;
    width: 200px;
    height: 120px;
    background: #34495e;
    border-radius: 10px;
    padding: 10px;
}

.screen {
    width: 100%;
    height: 100%;
    background: #2c3e50;
    border-radius: 5px;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.code-lines {
    display: flex;
    flex-direction: column;
    gap: 5px;
    margin-bottom: 10px;
}

.line {
    height: 3px;
    background: #3498db;
    border-radius: 2px;
}

.line:nth-child(1) {
    width: 40px;
}

.line:nth-child(2) {
    width: 60px;
}

.line:nth-child(3) {
    width: 30px;
}

.line:nth-child(4) {
    width: 50px;
}

.code-tag {
    color: #e74c3c;
    font-size: 20px;
    font-weight: bold;
}

.gears {
    position: absolute;
    top: 0;
    right: 20px;
}

.gear {
    font-size: 30px;
    animation: rotate 3s linear infinite;
}

.gear-1 {
    color: #f39c12;
}

.gear-2 {
    color: #3498db;
    margin-left: -10px;
    animation-direction: reverse;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

.person {
    position: absolute;
    bottom: 0;
}

.person-left {
    left: 20px;
}

.person-right {
    right: 20px;
}

.person-body {
    width: 30px;
    height: 40px;
    background: #e67e22;
    border-radius: 15px 15px 5px 5px;
}

.person-head {
    width: 20px;
    height: 20px;
    background: #f4d03f;
    border-radius: 50%;
    margin: -5px auto 0;
}

.database {
    position: absolute;
    bottom: 20px;
    left: 120px;
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.db-layer {
    width: 40px;
    height: 8px;
    background: #3498db;
    border-radius: 4px;
}

.form-section {
    flex: 1;
    padding: 60px 40px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.system-title {
    font-size: 24px;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 40px;
    text-align: center;
}

.login-form {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
}

.form-input {
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 16px;
    transition: border-color 0.3s;
}

.form-input:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.captcha-group {
    display: flex;
    gap: 10px;
    align-items: center;
}

.captcha-input {
    flex: 1;
}

.captcha-display {
    width: 80px;
    height: 50px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    font-weight: bold;
    font-size: 18px;
    cursor: pointer;
    user-select: none;
    letter-spacing: 2px;
}

.captcha-display:hover {
    opacity: 0.8;
}

.login-button {
    padding: 15px;
    background: #3498db;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: background-color 0.3s;
    margin-top: 10px;
}

.login-button:hover:not(:disabled) {
    background: #2980b9;
}

.login-button:disabled {
    background: #bdc3c7;
    cursor: not-allowed;
}

.error-message {
    color: #e74c3c;
    text-align: center;
    margin-top: 15px;
    font-size: 14px;
}

@media (max-width: 768px) {
    .login-card {
        flex-direction: column;
        max-width: 400px;
    }

    .illustration-section {
        min-height: 200px;
    }

    .form-section {
        padding: 40px 30px;
    }

    .system-title {
        font-size: 20px;
    }
}
</style>